package com.jwb.pub.controller;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jwb.pub.dao.BaseDAO;
import com.jwb.pub.model.JavaModel;
import com.jwb.pub.service.DeptService;
import com.jwb.util.MainController;
import com.jwb.util.ToolsUtil;


@Slf4j
@Controller
@RequestMapping(value="/pub/dept" )
@SessionAttributes(value = { "userId" })
public class DeptController extends MainController{


	@Autowired  
	private DeptService deptService;
	
	@Autowired
	private BaseDAO baseDAO;
	
	
	
    
    /**
     * http://127.0.0.1:8080/ssm/pub/dept/deptTreeEx?id=0
     * @param req
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/deptTreeEx")
    @ResponseBody
	public String deptTreeEx(HttpServletRequest req)
	{
    	JSONObject result = new JSONObject();
    	HttpSession session = req.getSession();
    	String userId=(String)session.getAttribute("userId") == null ? "" : (String)session.getAttribute("userId");
    	String realName=(String)session.getAttribute("realName") == null ? "" : (String)session.getAttribute("realName");
    	String curDeptName=(String)session.getAttribute("curDeptName") == null ? "" : (String)session.getAttribute("curDeptName");
    	String curDeptId=(String)session.getAttribute("curDeptId") == null ? "" : (String)session.getAttribute("curDeptId");
    	String curDeptLevel=(String)session.getAttribute("curDeptLevel") == null ? "" : (String)session.getAttribute("curDeptLevel");
    	String rank=(String)session.getAttribute("rank") == null ? "" : (String)session.getAttribute("rank");
    	String deptCode=(String)session.getAttribute("deptCode") == null ? "" : (String)session.getAttribute("deptCode");
    	String groupCode=(String)session.getAttribute("groupCode") == null ? "" : (String)session.getAttribute("groupCode");
    	String rankDeptId=(String)session.getAttribute("rankDeptId") == null ? "" : (String)session.getAttribute("rankDeptId");
    	String removeChild = req.getParameter("removeChild") == null ? ""
				: req.getParameter("removeChild");
    	String showAll = req.getParameter("removeChild") == null ? ""
				: req.getParameter("showAll");
    	String showRang = "";
    	String treeLevelPro ="";
    	try{
    		showRang = ToolsUtil.getProp("config.properties", "showRang");
    		treeLevelPro = ToolsUtil.getProp("config.properties", "treeLevel");
    	}catch(Exception e){
    		e.printStackTrace();
    		result.put("respCode", "999");
    		result.put("respDesc", "获取config数据失败");
    		return result.toString();
    	}
    	
    	String id="";
    	if("0".equals(showRang))
    	{
    		 id=req.getParameter("id"); 
    	}
    	else if ("2".equals(showRang))
    	{
    		 id=rankDeptId; 
    	}
    	else if ("1".equals(showRang))
    	{
    		//到底以谁为主看需求
    		id=rankDeptId; 
    	}    	
    	
    	log.info("deptTreeEx((showRang="+showRang+");(userId="+userId+");(realName="+realName+");(rank="+rank+");(rankDeptId="+rankDeptId+");(deptCode="+deptCode+");(groupCode="+groupCode+");curDeptLevel="+curDeptLevel+");(curDeptId="+curDeptId+");(curDeptName="+curDeptName+");");
    	//前台deptId=1;
    	
        //构造当前部门节点
    	JSONArray array = new JSONArray();
    	JSONObject jsobject = new JSONObject();		
    	jsobject=deptService.getDeptInfo(id);
    	if ("0".equals(jsobject.getString("respCode"))&&jsobject.getJSONArray("list").size()>0) {
    		
    		JSONObject obj = new JSONObject();
    		
    		int deptcount=deptService.getDeptCount(String.valueOf(jsobject.getJSONArray("list").getJSONObject(0).getInteger("dept_id")), treeLevelPro);
    		if("".equals(showAll))
			{
    			deptcount=1;
			}
    		
    		if(deptcount>0)
    		{	
    			obj.put("value", jsobject.getJSONArray("list").getJSONObject(0).getString("dept_id"));
    			obj.put("id", jsobject.getJSONArray("list").getJSONObject(0).getString("dept_id"));
				obj.put("pId", jsobject.getJSONArray("list").getJSONObject(0).getString("dept_parent_id"));
				obj.put("label", jsobject.getJSONArray("list").getJSONObject(0).getString("dept_name"));	
				JSONArray jsonarray=deptService.loadTree(id,removeChild,showAll);
				if(!"".equals(removeChild))
				{
					if(jsonarray.size()>0)
					{
						obj.put("children", jsonarray);
					}
				}
				else
				{
					obj.put("children", jsonarray);
				}
				
						
				//obj.put("children", deptService.loadTree(id));
				obj.put("deptId", jsobject.getJSONArray("list").getJSONObject(0).getString("dept_id"));					
				obj.put("deptName", jsobject.getJSONArray("list").getJSONObject(0).getString("dept_name"));
				obj.put("deptParentId", jsobject.getJSONArray("list").getJSONObject(0).getString("dept_parent_id"));
				obj.put("deptLevel", jsobject.getJSONArray("list").getJSONObject(0).getString("dept_level"));
	    		
				array.add(obj);
    		}
    		
    		result.put("tree", array);
    		result.put("respCode", "0");
    		result.put("respDesc", "OK");
    		
    	}else{
    		result.put("respCode", "-1");
    		result.put("respDesc", "访问"+id+"部门信息失败");
    		
    	}
    	
    	
    	//JSONArray array =deptService.loadTree(    	deptService.getDeptInfo(id).getJSONArray("list").getJSONObject(0).getString("dept_parent_id"));			
    	//JSONArray array2 =deptService.loadTree(id);			
    	//log.info("deptTreeEx "+array2);
    	log.info("deptTreeEx "+result.toString());
    	
		return result.toString();
	}
    
    /**
     * http://127.0.0.1:8080/ssm/pub/dept/deptTreeEx2?id=0
     * @param req
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/deptTreeEx2")
    @ResponseBody
	public String deptTreeEx2(HttpServletRequest req) throws Exception
	{
    	String showAll = req.getParameter("removeChild") == null ? ""
				: req.getParameter("showAll");
    	String treeLevelPro = ToolsUtil.getProp("config.properties", "treeLevel");
    	String removeChild = req.getParameter("removeChild") == null ? ""
				: req.getParameter("removeChild");
    	//前台deptId=1;
    	String id=req.getParameter("id"); 
        //构造当前部门节点
    	JSONArray array = new JSONArray();
    	JSONObject jsobject = new JSONObject();		
    	jsobject=deptService.getDeptInfo(id);
    	if ("0".equals(jsobject.getString("respCode"))&&jsobject.getJSONArray("list").size()>0) {
    		
    		JSONObject obj = new JSONObject();
    		int deptcount=deptService.getDeptCount(jsobject.getJSONArray("list").getJSONObject(0).getString("dept_id"), treeLevelPro);
    		if("".equals(showAll))
			{
    			deptcount=1;
			}
    		if(deptcount>0)
    		{
    			        obj.put("value", jsobject.getJSONArray("list").getJSONObject(0).getString("dept_id"));
    			        obj.put("id", jsobject.getJSONArray("list").getJSONObject(0).getString("dept_id"));
						obj.put("pId", jsobject.getJSONArray("list").getJSONObject(0).getString("dept_parent_id"));
						obj.put("label", jsobject.getJSONArray("list").getJSONObject(0).getString("dept_name"));
						JSONArray jsonarray=deptService.loadTree(id,removeChild,showAll);
						if(!"".equals(removeChild))
						{
							if(jsonarray.size()>0)
							{
								obj.put("children", jsonarray);
							}
						}
						else
						{
							obj.put("children", jsonarray);
						}
						//obj.put("children", deptService.loadTree(id));
						obj.put("deptId", jsobject.getJSONArray("list").getJSONObject(0).getString("dept_id"));					
						obj.put("deptName", jsobject.getJSONArray("list").getJSONObject(0).getString("dept_name"));
						obj.put("deptParentId", jsobject.getJSONArray("list").getJSONObject(0).getString("dept_parent_id"));
						obj.put("deptLevel", jsobject.getJSONArray("list").getJSONObject(0).getString("dept_level"));
			    		
						array.add(obj);
    		}
    	}
    	
    	
    	//JSONArray array =deptService.loadTree(    	deptService.getDeptInfo(id).getJSONArray("list").getJSONObject(0).getString("dept_parent_id"));			
    	//JSONArray array2 =deptService.loadTree(id);			
    	//log.info("deptTreeEx "+array2);
    	log.info("deptTreeEx2 "+array);
		return array.toString();
	}
    
    /**
	 * 
	 * @功能描述：取得部门详细信息
	 * 
	 * @author LIU CHANG
	 * 
	 * http://127.0.0.1:8080/ssm/pub/dept/deptMain?deptId=0&deptLevel=0
	 * 
	 * @return
	 * @createDate 2018.3.21
	 * @createTime 10:47:30 AM
	 * 
	 */
    @RequestMapping("/deptMain")
    @ResponseBody
	public String deptMain(HttpServletRequest req) 
	{
		String deptId = req.getParameter("deptId");
		String deptLevel = req.getParameter("deptLevel");
		String privNames = (String)req.getSession().getAttribute("privNames");
		boolean haveRight=false,addRight= false, editRight=false, delRight=false;
		if(privNames.indexOf("dept_manage")>=0){
			haveRight =true;
		}
		JSONObject jsobject = new JSONObject();
		if(null==deptId || "".equals(deptId)){
			deptId = (String)req.getSession().getAttribute("curDeptId");			
		}
		String sql= "select d.dept_id, d.dept_name, d.dept_parent_id, ( select t.dept_name from dept t where t.dept_id=d.dept_parent_id and dept_sts='A') dept_parent_name, d.dept_order, d.dept_sts, d.remarks, d.dept_level, d.kp_join, d.task_num, d.duty_name, d.duty_phone  from dept d "
				+" where d.dept_id="+deptId+" AND d.dept_sts='A'";
		try {

	    	int levelLimit=Integer.valueOf(ToolsUtil.getProp("config.properties", "treeLevel"));  	
	    	
	    	
	    	JSONObject jso=baseDAO.findBySqlToJosn(sql);		
			if(jso.getJSONArray("list").size()>0){
				if(null==deptLevel|| "".equals(deptLevel)){
					deptLevel = String.valueOf(jso.getJSONArray("list").getJSONObject(0).getInteger("dept_level"));
				}
				jsobject.put("deptId", jso.getJSONArray("list").getJSONObject(0).getInteger("dept_id"));
				jsobject.put("deptName", jso.getJSONArray("list").getJSONObject(0).getString("dept_name"));
				jsobject.put("deptParentId", jso.getJSONArray("list").getJSONObject(0).getInteger("dept_parent_id"));
				jsobject.put("deptParentName", jso.getJSONArray("list").getJSONObject(0).getString("dept_parent_name"));
				jsobject.put("deptOrder", jso.getJSONArray("list").getJSONObject(0).getInteger("dept_order"));
				jsobject.put("deptSts", jso.getJSONArray("list").getJSONObject(0).getString("dept_sts"));
				jsobject.put("deptRemarks", jso.getJSONArray("list").getJSONObject(0).getString("remarks"));
				jsobject.put("deptLevel", deptLevel);
				jsobject.put("kpJoin", jso.getJSONArray("list").getJSONObject(0).getString("kp_join"));	
				jsobject.put("taskNum", jso.getJSONArray("list").getJSONObject(0).getString("task_num"));	
				jsobject.put("dutyName", jso.getJSONArray("list").getJSONObject(0).getString("duty_name"));	
				jsobject.put("dutyPhone", jso.getJSONArray("list").getJSONObject(0).getString("duty_phone"));	
				int level = Integer.valueOf(deptLevel);
				
				if(haveRight){
					if(level<levelLimit){
						addRight =true;	  
					}
					String childSql= "SELECT count(*) From dept where dept_sts='A' and dept_parent_id="+deptId;
					int cnt = baseDAO.findBySqlCnt(childSql);
					if(cnt==0){
						delRight=true;
					}
					editRight=true;
				}
				
				sql="select sum(IFNULL(task_num,0)) from user_info where cur_dept_id="+deptId+" and sts='A' and kp_join='1' ";
				String total = String.valueOf(baseDAO.findBySqlCnt(sql));
				jsobject.put("totalTask", total);
				
				jsobject.put("deptAdd", deptService.getButtonInfo("添加", addRight));
				jsobject.put("deptEdit", deptService.getButtonInfo("编辑", editRight));
				jsobject.put("deptDel", deptService.getButtonInfo("删除", delRight));
				
				jsobject.put("respCode", "0");
				jsobject.put("respDesc", "OK");
			}else{
				jsobject.put("respCode", "1");
				jsobject.put("respDesc", "没有数据");
			}			
		} catch (Exception e) {
			jsobject.put("respCode", "9");
			jsobject.put("respDesc", "数据查找失败");

		}
		log.info("deptMain "+jsobject.toString());
		return jsobject.toString();
	}
    
    
    
    /**
	 * 
	 * @功能描述：编辑部门
	 * 
	 * @author LIU CHANG
	 * 
	 * @return
	 * @throws DBException
	 * @createDate Mar 21, 2018
	 * @createTime 3:40:41 PM
	 * 
	 */
    @RequestMapping("/deptEdit")
    @ResponseBody
	public String deptEdit(HttpServletRequest req)
	{
		JSONObject jsobject = new JSONObject();
		String deptId = req.getParameter("deptId");
		String sql= "SELECT t.dept_id, t.dept_name, t.dept_parent_id, (select d.dept_name from dept d where d.dept_id = t.dept_parent_id and d.dept_sts='A') dept_parent_name, t.dept_order, t.remarks " 
				+ " FROM dept t where t.dept_sts ='A' AND t.dept_id='"+deptId+"'";
		try {
			JSONObject jso =baseDAO.findBySqlToJosn(sql);
			JSONArray array = jso.getJSONArray("list");
		   
			if(!array.isEmpty()||array!=null){
				JSONObject obj =array.getJSONObject(0);
				jsobject.put("deptId", obj.getString("dept_id"));
				jsobject.put("deptName", obj.getString("dept_name"));
				jsobject.put("deptParentId", obj.getString("dept_parent_id"));
				jsobject.put("deptParentName", obj.getString("dept_parent_name"));
				jsobject.put("deptOrder", obj.getString("dept_order"));
				jsobject.put("deptRemarks",obj.getString("remarks"));
				jsobject.put("respCode", "0");
				jsobject.put("respDesc", "OK");
			}
			else{
				jsobject.put("respCode","1");
				jsobject.put("respDesc","没有数据");
			}
		} catch (Exception e) {
			jsobject.put("respCode", "9");
			jsobject.put("respDesc", "数据查找失败");
			return jsobject.toString();
		}

		return jsobject.toString();
	}
    
    
    
    /**
	 * 
	 * @功能描述：删除部门
	 * 
	 * @author LIU CHANG
	 * http://127.0.0.1:8080/ssm/pub/dept/deptDel?deptId=0
	 * 
	 * @return
	 * @throws DBException
	 * @createDate Mar 21, 2018
	 * @createTime 3:40:41 PM
	 * 
	 */
    @RequestMapping("/deptDel")
    @ResponseBody
	public String deptDel(HttpServletRequest req) 
	{
    	HttpSession session = req.getSession();
    	String operCode= (String)session.getAttribute("userId");
		JSONObject jsobject = new JSONObject();
		String deptId = req.getParameter("deptId");
		String pSql = "select dept_parent_id, (SELECT dept_level FROM dept WHERE dept_id = d.dept_parent_id) dept_parent_level from dept d where dept_id ="+deptId+" and dept_sts = 'A'";
		JSONArray array = new JSONArray();
		try {
			array = baseDAO.findBySqlToJosn(pSql).getJSONArray("list");
			String deptParentId = array.getJSONObject(0).getString("dept_parent_id");
			String deptParentLevel = array.getJSONObject(0).getString("dept_parent_level");
			String delSql = "Update dept SET dept_sts='P',oper_code=?  WHERE dept_id=? and dept_sts='A'";
			ArrayList<JavaModel> list = new ArrayList<>();
			list.add(new JavaModel(operCode));
			list.add(new JavaModel(Integer.valueOf(deptId)));
			boolean result = baseDAO.excuteSql(delSql, list);
			if(result){
				jsobject.put("deptId", deptParentId);
				jsobject.put("deptLevel", deptParentLevel);
				jsobject.put("updateTree", "1");
				jsobject.put("respCode", "0");
				jsobject.put("respDesc", "OK");
			}
			else{
				jsobject.put("deptId", deptId);
				jsobject.put("updateTree", "0");
				jsobject.put("respCode", "1");
				jsobject.put("respDesc", "操作失败，该部门下可能还有员工");
			}
		} catch (Exception e) {
			jsobject.put("deptId", deptId);
			jsobject.put("updateTree", "0");
			jsobject.put("respCode", "1");
			jsobject.put("respDesc", "操作失败，该部门下可能还有员工");
		}
		
		log.info("deptDel "+jsobject.toJSONString());
		return jsobject.toString();
	}
    
    
    /**
	 * 
	 * @功能描述：保存部门
	 * 
	 * @author LIU CHANG
	 * http://127.0.0.1:8080/ssm/pub/dept/deptSave?deptName=0&deptParentId=&deptId=&deptOrder=&remarks=&deptLevel=&kpJoin=&taskNum=
	 * @return
	 * @throws DBException
	 * @createDate Mar 21, 2018
	 * @createTime 3:54:07 PM
	 * 
	 */
    @RequestMapping("/deptSave")
    @ResponseBody
	public String deptSave(HttpServletRequest req)
	{
		JSONObject jsobject = new JSONObject();
		String deptName= req.getParameter("deptName").trim();
		String deptParentId = req.getParameter("deptParentId");
		String deptId =req.getParameter("deptId");
		String deptOrder = req.getParameter("deptOrder");
		String remarks = req.getParameter("remarks") == null ?"":req.getParameter("remarks");
		String deptLevel =req.getParameter("deptLevel");
		String kpJoin = req.getParameter("kpJoin") == null ?"":req.getParameter("kpJoin");
		String taskNum = req.getParameter("taskNum") == null ?"":req.getParameter("taskNum");
		HttpSession hsession = req.getSession();
		String operCode = (String)hsession.getAttribute("userId");
		
		if ("".equals(deptOrder) || null == deptOrder){
			   deptOrder = "1";
		}
		String sql = "SELECT count(*) from dept where dept_sts='A' and dept_name='"+deptName+"' and dept_parent_id="+deptParentId;
		if(null !=deptId &&!"".equals(deptId)){
			sql +=" and dept_id <> "+deptId;  
		}
		try {
			int size = baseDAO.findBySqlCnt(sql);
			if(size==0){
				

				  
			   if(null ==deptId ||"".equals(deptId)){
					  SqlSession session = null;
					  Connection conn = null;
					  PreparedStatement ps = null;
					  PreparedStatement ps2 = null;
					  deptLevel = String.valueOf(Integer.valueOf(deptLevel)+1);
					  try{
						  session = baseDAO.getSession();
						  conn = session.getConnection();
						  conn.setAutoCommit(false);
						  String addSql="";
						  int idx = 1;
//						  addSql="INSERT INTO dept (dept_parent_id,dept_name,remarks, dept_order, dept_sts,dept_level,kp_join, task_num, oper_code)"
//								  +" VALUES(?,?,?,?,'C',?,?,?,?)";
//						  ps= conn.prepareStatement(addSql);						  
//						  ps.setInt(idx++, Integer.valueOf(deptParentId));
//						  ps.setString(idx++, deptName);
//						  ps.setString(idx++, remarks);
//						  ps.setInt(idx++, Integer.valueOf(deptOrder));
//						  ps.setInt(idx++, Integer.valueOf(deptLevel));
//						  ps.setString(idx++, kpJoin);
//						  ps.setString(idx++, taskNum);
//						  ps.setString(idx++, operCode);
//						  ps.addBatch();
						  addSql="INSERT INTO dept (dept_parent_id,dept_name,remarks, dept_order, dept_sts,dept_level,kp_join, task_num, oper_code)"
								  +" VALUES(?,?,?,?,'A',?,?,?,?)";
						  ps2= conn.prepareStatement(addSql);	
						  idx = 1;						 
						  ps2.setInt(idx++, Integer.valueOf(deptParentId));
						  ps2.setString(idx++, deptName);
						  ps2.setString(idx++, remarks);
						  ps2.setInt(idx++, Integer.valueOf(deptOrder));
						  ps2.setInt(idx++, Integer.valueOf(deptLevel));
						  ps2.setString(idx++, kpJoin);
						  ps2.setString(idx++, taskNum);
						  ps2.setString(idx++, operCode);
						  ps2.addBatch();						  
//						  ps.executeBatch();
						  ps2.executeBatch();
						  conn.commit();
						  sql= "select dept_id from dept where dept_parent_id ="+deptParentId+" and dept_name='"+deptName+"' and dept_sts='A' ";
						  JSONObject obj = baseDAO.findBySqlToJosn(sql).getJSONArray("list").getJSONObject(0);
						  deptId = obj.getString("dept_id");						  
						  jsobject.put("respCode", "0");
						  jsobject.put("respDesc", "OK");
					  }catch(Exception e){
						 e.printStackTrace();
						 try{
							conn.rollback();
							jsobject.put("respCode", "002");
							jsobject.put("respDesc", "更新数据库失败");
						}catch(SQLException e1){
							e1.printStackTrace();
						}
					  }finally{
						  try {
							  	if (ps != null) {
									ps.close();
								}
								if (ps2 != null) {
									ps2.close();
								}
								if (conn != null) {
									conn.close();
								}
								if (session != null) {
									session.close();
								}

							} catch (Exception e) {
							}
						  	baseDAO.closeSession(session);
					  }
				  
			  }else{
				  String stsUpdate = req.getParameter("stsUpdate"); 
				  if(stsUpdate.equals("false")){
					  // oper_date=sysdate
					  
					  String updateSql = "UPDATE dept SET dept_name=?, remarks=?, dept_order=?,oper_code=?  WHERE dept_id=? and dept_sts='A' and dept_level=? ";
					  ArrayList<JavaModel> list = new ArrayList<>();
					  Collections.addAll(list, new JavaModel(deptName), new JavaModel(remarks), new JavaModel(Integer.valueOf(deptOrder)), new JavaModel(operCode),new JavaModel(Integer.valueOf(deptId)),new JavaModel(Integer.valueOf(deptLevel)));
					  if(baseDAO.excuteSql(updateSql,list)){
						  jsobject.put("respCode", "0");
						  jsobject.put("respDesc", "OK");
					  }else{
						  jsobject.put("respCode", "002");
						  jsobject.put("respDesc", "更新数据库失败");
					  }					  
					  
				  }else if(stsUpdate.equals("true")){
					  Map<String,ArrayList<JavaModel>> map = new HashMap<>();
					  String updateSql = "UPDATE dept SET dept_sts='C'  WHERE dept_id=? and dept_sts='A' and dept_level=?";
					  ArrayList<JavaModel> list = new ArrayList<>();
					  Collections.addAll(list, new JavaModel(Integer.valueOf(deptId)), new JavaModel(Integer.valueOf(deptLevel)));
					  map.put(updateSql, list);
					  String addSql= "INSERT INTO dept (dept_id,dept_parent_id,dept_name,remarks, dept_order, dept_sts,dept_level,kp_join, task_num, oper_code)"
							  +" VALUES(?,?,?,?,?,'A',?,?,?,?)";
					  list = new ArrayList<>();
					  Collections.addAll(list, new JavaModel(Integer.valueOf(deptId)),new JavaModel(Integer.valueOf(deptParentId)), new JavaModel(deptName),new JavaModel(remarks),
							  new JavaModel(Integer.valueOf(deptOrder)), new JavaModel(Integer.valueOf(deptLevel)), new JavaModel(kpJoin), new JavaModel(taskNum), new JavaModel(operCode)
					  );
					  map.put(addSql, list);
					  if(baseDAO.excuteBatchSql(map)){
						  jsobject.put("respCode", "0");
						  jsobject.put("respDesc", "OK");
					  }else{
						  jsobject.put("respCode", "002");
						  jsobject.put("respDesc", "更新数据库失败");
					  }
					  
				  }				  
				  
			  }
				
			  jsobject.put("deptName", deptName);
			  jsobject.put("deptParentId", deptParentId);
			  jsobject.put("deptId", deptId);
			  jsobject.put("remarks", remarks);
			  jsobject.put("deptOrder", deptOrder);
			  jsobject.put("deptSts", "A");
			  jsobject.put("kpJoin", kpJoin);
			  jsobject.put("taskNum", taskNum);
			  jsobject.put("deptLevel", deptLevel);
			  jsobject.put("updateTree", "1");				
				
			}else{
				jsobject.put("deptName", deptName);
				jsobject.put("deptParentId", deptParentId);
				jsobject.put("deptId", deptId);
				jsobject.put("remarks", remarks);
				jsobject.put("deptOrder", deptOrder);
				jsobject.put("deptLevel", deptLevel);
				jsobject.put("deptSts", "A");
				jsobject.put("updateTree", "0");
				jsobject.put("respCode", "1");
				jsobject.put("respDesc", "部门已存在");
			}
			
		} catch (Exception e) {
			jsobject.put("deptName", deptName);
			jsobject.put("deptParentId", deptParentId);
			jsobject.put("deptId", deptId);
			jsobject.put("deptLevel", deptLevel);
			jsobject.put("updateTree", "0");
			jsobject.put("respCode", "9");
			jsobject.put("respDesc", "查找部门失败");	
		}
		
		return jsobject.toString();
	}
    
    
    
    /**
	 * 
	 * @功能描述：添加部门
	 * 
	 * @author LIU CHANG
	 * 
	 * @return
	 * @createDate Mar 21, 2018
	 * @createTime 4:09:40 PM
	 * 
	 */
    @RequestMapping("/deptAdd")
    @ResponseBody
	public String deptAdd(HttpServletRequest req)
	{
		String deptParentId = req.getParameter("deptParentId");
		JSONObject jsobject = new JSONObject();
		
		String sql="SELECT (SELECT t.dept_name FROM dept t WHERE t.dept_id = d.dept_parent_id) deptParentName FROM dept d Where d.dept_id="+deptParentId;
		
		
		try {
			 JSONObject jso = baseDAO.findBySqlToJosn(sql);
			if(jso.getJSONArray("list").size()>0){
				jsobject.put("deptParentId", deptParentId);
				jsobject.put("deptParentName", jso.getJSONArray("list").getJSONObject(0).getString("deptParentName"));
				jsobject.put("respCode", "0");
				jsobject.put("respDesc", "OK");
			}else{
				jsobject.put("respCode", "1");
				jsobject.put("respDesc", "没有数据");
			}
			
		} catch (Exception e) {
			jsobject.put("respCode", "9");
			jsobject.put("respDesc", "查找数据失败");
			return jsobject.toString();
		}
		
		return jsobject.toString();
				
	}
    
    
    /**
     * http://127.0.0.1:8080/myservices/dept/deptuserlist.mvc?id=0
     * @param req
     * @return
     */
    @RequestMapping("/deptuserlist")
    @ResponseBody
	public String deptuserlist(HttpServletRequest req)
	{
    	String id = req.getParameter("id") == null ? "" : req.getParameter("id");        
		JSONObject jsobject = new JSONObject();
		JSONObject jso = new JSONObject();
		try {
			jsobject=deptService.getDeptListHead(id);
			jso.put("listhead", jsobject.getJSONArray("list"));
			log.info("deptuserlist - getDeptListHead "+jsobject.toString());
			jsobject=deptService.getDeptuserlist(id);
			log.info("deptuserlist - getDeptuserlist  "+jsobject.toString());
			jso.put("respCode", "0");
			jso.put("respDesc", "数据获取成功");			
			jso.put("list", jsobject.getJSONArray("list"));
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			jso.put("respCode", "-1");
			jso.put("respDesc", "数据异常");
		}
		
		
		return jso.toString();
				
	}
    
    @RequestMapping("/deptConfigSave")
    @ResponseBody
	public String deptConfigSave(HttpServletRequest req)
	{
		JSONObject jsobject = new JSONObject();
		String deptLevel = req.getParameter("deptLevel") == null ? "" : req.getParameter("deptLevel");
		String deptChange = req.getParameter("deptChange") == null ? "" : req.getParameter("deptChange");
		String deptId = req.getParameter("deptId") == null ? "" : req.getParameter("deptId");        
		String deptPriv = req.getParameter("deptPriv") == null ? "" : req.getParameter("deptPriv");
		String roleCheck = req.getParameter("roleCheck") == null ? "" : req.getParameter("roleCheck");
		String roleList = req.getParameter("roleList") == null ? "" : req.getParameter("roleList");

		String sql = "SELECT count(*) from DEPT_CONFIG where dept_id = '"
				+ deptId + "'";

		try {
			int size = baseDAO.findBySqlCnt(sql);
			if (size == 0) {
				String addSql = "insert into dept_config (dept_level, dept_change, dept_priv, role_check, role_list, dept_id) values"
						+ " ('"
						+ deptLevel
						+ "','"
						+ deptChange
						+ "','"
						+ deptPriv
						+ "','"
						+ roleCheck
						+ "','"
						+ roleList
						+ "','" + deptId + "')";
				baseDAO.excuteSql(addSql,null);

			} else {
				// DeptName remarks DeptOrder
				String updateSql = "update dept_config set dept_level = '"
						+ deptLevel + "',dept_change = '" + deptChange
						+ "',dept_priv = '" + deptPriv + "',role_check = '"
						+ roleCheck + "',role_list = '" + roleList
						+ "' where dept_id='" + deptId + "'";
				baseDAO.excuteSql(updateSql,null);
			}

			jsobject.put("deptLevel", deptLevel);
			jsobject.put("deptChange", deptChange);
			jsobject.put("deptId", deptId);
			jsobject.put("deptPriv", deptPriv);
			jsobject.put("roleCheck", roleCheck);
			jsobject.put("roleList", roleList);
			jsobject.put("respCode", "0");
			jsobject.put("respDesc", "保存成功");

		} catch (Exception e) {
			jsobject.put("deptLevel", deptLevel);
			jsobject.put("deptChange", deptChange);
			jsobject.put("deptId", deptId);
			jsobject.put("deptPriv", deptPriv);
			jsobject.put("roleCheck", roleCheck);
			jsobject.put("roleList", roleList);
			jsobject.put("respCode", "9");
			jsobject.put("respDesc", "保存失败");
		}

		return jsobject.toString();
	}
    @RequestMapping("/deptConfigList")
    @ResponseBody
	public String deptConfigList(HttpServletRequest req)
	{
    	String deptId = req.getParameter("deptId") == null ? "" : req.getParameter("deptId");        
		JSONObject jsobject = new JSONObject();
		JSONObject jso = new JSONObject();
		try {
			
			jsobject=deptService.getDeptConfigList(deptId);

			jso.put("respCode", "0");
			jso.put("respDesc", "数据获取成功");			
			jso.put("list", jsobject.getJSONArray("list"));
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			jso.put("respCode", "-1");
			jso.put("respDesc", "数据异常");
		}
		
		
		return jso.toString();
				
	}
    
    @RequestMapping("/deptConfigDel")
    @ResponseBody
	public String deptConfigDel(HttpServletRequest req)
	{
    	String deptId = req.getParameter("deptId") == null ? "" : req.getParameter("deptId");        
		JSONObject jsobject = new JSONObject();
		try {

			String sql="delete dept_config where dept_id='"+deptId+"'";
			baseDAO.excuteSql(sql,null);
			jsobject.put("respCode", "0");
			jsobject.put("respDesc", "删除成功");			
			jsobject.put("deptId", deptId);
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			jsobject.put("respCode", "-1");
			jsobject.put("respDesc", "删除失败");
		}
		
		
		return jsobject.toString();
				
	}
    
    /**
     * http://127.0.0.1:8080/khservices/dept/deptlist.mvc?deptlevel=2
     * @param req
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/deptlist")
    @ResponseBody
	public String deptlist(HttpServletRequest req) throws Exception
	{
    	HttpSession session = req.getSession();
    	JSONObject jsobject = new JSONObject();
    	String deptlevel = req.getParameter("deptlevel") == null ? "" : req
				.getParameter("deptlevel");
    	
    	/**
    	 * deptshow=6   
    	 */
    	String   deptshow = req.getParameter("deptshow") == null ? "" : req
				.getParameter("deptshow");
    	//deptshow="8";
    	
    	String userId = (String) session.getAttribute("userId") == null ? ""
				: (String) session.getAttribute("userId");
		String rank = (String) session.getAttribute("rank") == null ? ""
				: (String) session.getAttribute("rank");
		String deptCode = (String) session.getAttribute("deptCode") == null ? ""
				: (String) session.getAttribute("deptCode");
		String groupCode = (String) session.getAttribute("groupCode") == null ? ""
				: (String) session.getAttribute("groupCode");
		String rankDeptId = (String) session.getAttribute("rankDeptId") == null ? ""
				: (String) session.getAttribute("rankDeptId");
		String privNames = (String) session.getAttribute("privNames") == null ? ""
				: (String) session.getAttribute("privNames");
		
		StringBuffer s = new StringBuffer();
		s.append("userId="+userId).append("\n");
		s.append("rank="+rank).append("\n");
		s.append("deptlevel="+deptlevel).append("\n");
		s.append("privNames="+privNames).append("\n");		
		s.append("deptCode="+deptCode).append("\n");
		s.append("groupCode="+groupCode).append("\n");
		s.append("rankDeptId="+rankDeptId).append("\n");
		log.info("deptlist()-output:" + s.toString());
		
    	try
      	{      		 
      		 String sqlWhere="";
      		 String sqlOrder="";
			 String sql="select dept_id, dept_name "+
						"  from dept "+
						" where dept_sts = 'A' ";					
						
			    if (null != deptlevel && !"".equals(deptlevel))
				{
					sqlWhere += " and dept_level = '"+deptlevel+"'";
				}   
			    //所有部门	
			    if("0".equals(deptshow))
			    {
			    	sqlWhere+="";
			    }
			    //初评所有部门	
			    if("1".equals(deptshow))
			    {
			    	sqlWhere+="  and dept_id in (select dept_code from user_info where sts='A' and kp_person='1')";
			    }
			    //终评所有部门	
			    else if("2".equals(deptshow))
			    {
			    	sqlWhere+="  and dept_id in (select dept_code from user_info where sts='A' and kp_person='2')";
			    }
			    //本部门		
			    else if("3".equals(deptshow))
			    {
			    	sqlWhere+="  and dept_id='"+deptCode+"'";
			    	
			    }
			    
			    //初评本部门			
			    else if("4".equals(deptshow))
			    {
			    	sqlWhere+="  and dept_id='"+deptCode+"'";
			    	sqlWhere+="  and dept_id in (select dept_code from user_info where sts='A' and kp_person='1')";
			    	
			    }
			    
			    
			    //终评本部门				
			    else if("5".equals(deptshow))
			    {
			    	sqlWhere+="  and dept_id='"+deptCode+"'";
			    	sqlWhere+="  and dept_id in (select dept_code from user_info where sts='A' and kp_person='1')";
			    	
			    }
			    
			    
			    //部门(rank决定)					
			    else if("6".equals(deptshow))
			    {
			    	
			    	//二层所有部门
			    	if("rank_1".equals(rank))
			    	{
			    		sqlWhere+="";
			    	}
			    	//当前部门
			    	else if("rank_2".equals(rank)||"rank_3".equals(rank))
			    	{
			    		sqlWhere+="  and dept_id='"+deptCode+"'";
			    	}
			    				    	
			    }
			   //初评部门(rank决定)			
			    else if("7".equals(deptshow))
			    {
			    	
			    	//rank="rank_3";
			    	//二层所有部门
			    	if("rank_1".equals(rank))
			    	{
			    		sqlWhere+="";
			    		sqlWhere+="  and dept_id in (select dept_code from user_info where sts='A' and kp_person='1')";
			    	}
			    	//当前部门
			    	else if("rank_2".equals(rank)||"rank_3".equals(rank))
			    	{
			    		sqlWhere+="  and dept_id='"+deptCode+"'";
			    		sqlWhere+="  and dept_id in (select dept_code from user_info where sts='A' and kp_person='1')";
			    	}
			    				    	
			    }
			    
			    //终评部门(rank决定)			
			    else if("8".equals(deptshow))
			    {
			    	
			    //rank="rank_3";
			    	//二层所有部门
			    	if("rank_1".equals(rank))
			    	{
			    		sqlWhere+="";
			    		sqlWhere+="  and dept_id in (select dept_code from user_info where sts='A' and kp_person='2')";
			    	}
			    	//当前部门
			    	else if("rank_2".equals(rank)||"rank_3".equals(rank))
			    	{
			    		sqlWhere+="  and dept_id='"+deptCode+"'";
			    		sqlWhere+="  and dept_id in (select dept_code from user_info where sts='A' and kp_person='2')";
			    	}
			    				    	
			    }
			    
			    else
			    {
			    	sqlWhere+="";
			    }
		  
		  
			    sqlOrder=" order by  dept_name desc";
			    sql+=sqlWhere+sqlOrder;	       
			    jsobject=baseDAO.findBySqlToJosn(sql);
      		
      	}   
      	catch(Exception e)
      	{
      		
      	}
      	
		
    	
    	
    	log.info("deptlist():" + jsobject.toString());

		return jsobject.toString();
	}
    
}
